import { SelectProps } from 'antd';

import { get, post } from '@/api';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useDictStore } from '@/store/dict';

export const useDataSource = () => {
  const { getNodeDataFor, currentAndParentPrivateVariables, currentAndParentPublicVariables } = useCurrentNode<any>();

  const [dataSetOptions, setDataSetOptions] = useState<SelectProps['options']>([]);
  const [tablesOptions, setTablesOptions] = useState<SelectProps['options']>([]);
  const [colsVariables, setColsVariables] = useState<VariableItem[]>([]);
  const { systemVars } = useDictStore();
  const rightVariables = useMemo(() => {
    return systemVars.concat(currentAndParentPublicVariables).concat(currentAndParentPrivateVariables);
  }, [currentAndParentPrivateVariables, currentAndParentPublicVariables, systemVars]);

  const getColsOptions = useCallback(() => {
    setTimeout(() => {
      const data = getNodeDataFor();
      if (!data?.dataSource || !data?.tableName) {
        setColsVariables([]);
        return;
      }
      get('/ds/columns', { tableName: data?.tableName!, dataSource: data?.dataSource! }).then((list) => {
        list.forEach((item) => {
          item.varLabel = item.varLabel || item.varName;
        });
        setColsVariables(list);
      });
    });
  }, [getNodeDataFor]);

  const getTables = useCallback((dsName?: string) => {
    setTimeout(() => {
      const data = getNodeDataFor();
      if (!data?.dataSource && !dsName) {
        setTablesOptions([]);
        return;
      }
      get('/ds/tables', { dataSource: dsName || data?.dataSource! }).then((list) => {
        setTablesOptions(list.map((name) => ({ label: name, value: name })));
      });
    });
  }, [getNodeDataFor]);

  useEffect(() => {
    post('/ds/page', {}).then((res) => {
      const options = res.list?.map((item) => {
        return {
          label: item.dbName,
          value: item.dsName,
          tableName: item.dbName
        };
      });
      setDataSetOptions(options);
    });
  }, []);

  useEffect(() => {
    getTables();
    getColsOptions();
  }, [getColsOptions, getTables]);

  return {
    getColsOptions,
    getTables,
    tablesOptions,
    dataSetOptions,
    colsVariables,
    rightVariables
  };
};
